package com.cavy.platform.client.service;

import com.cavy.platform.client.CavyConfig;
import com.cavy.platform.client.ErrorItem;
import com.cavy.platform.client.ResultInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.Collections;

/**
 * @author 唐旭
 * @Date 2018/7/26
 */
@Service
@Slf4j
public class AgentRegister {
    private static final String REGISTER_PATH = "/agent/register";
    @Autowired
    private CavyConfig cavyConfig;
    @Autowired
    private SystemInfoService infoService;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 向服务器注册
     */
    public void register() throws RuntimeException {
        HttpHeaders headers = new HttpHeaders();
        headers.put("Content-Type", Collections.singletonList(MediaType.APPLICATION_JSON_UTF8_VALUE));
        HttpEntity entity = new HttpEntity<>(infoService.buildAgentRegisterDto(), headers);
        ResponseEntity<ResultInfo> resultInfoResponseEntity = restTemplate.postForEntity(URI.create(cavyConfig.getHttpServerAddress() + REGISTER_PATH), entity, ResultInfo.class);
        ResultInfo resultInfoResponseEntityBody = resultInfoResponseEntity.getBody();
        if (!resultInfoResponseEntityBody.isSuccess()) {
            throw new RuntimeException("注册agent失败,原因:" + getErrorString(resultInfoResponseEntityBody));
        }
        log.info("注册到服务器成功...");
    }

    private String getErrorString(ResultInfo resultInfo) {
        StringBuilder builder = new StringBuilder();
        for (ErrorItem errorItem : resultInfo.getErrors()) {
            builder.append(errorItem.getMessage()).append(",");
        }
        if (builder.length() > 0) {
            builder.deleteCharAt(builder.length() - 1);
        }
        return builder.toString();
    }
}
